#include "mymusic.h"
#include"musiclist.h"
#include<QDebug>
#include<QFileDialog>
#include "ui_mymusic.h"
#include<QPushButton>
#include<QMouseEvent>
#include<QGraphicsDropShadowEffect>
#include<QJsonArray>
#include<QJsonObject>
#include"lrcpage.h"
MYMusic::MYMusic(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MYMusic)
    ,currentIndex(-1)
{
    ui->setupUi(this);
    Init();
    InitPlayer();

    connectSignalAndSlots();//处理信号和槽函数
}

MYMusic::~MYMusic()
{
    delete ui;
}

void MYMusic::Init()
{
    this->setWindowFlag(Qt::FramelessWindowHint);
    //设置窗口透明
    setAttribute(Qt::WA_TranslucentBackground);
    //设置阴影效果 在做Lrcpage动画效果的时候发现阴影效果会影响动画效果，所以就去掉了阴影效果
   // QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
        //shadowEffect->setOffset(0, 0);
        //shadowEffect->setColor("#000000");   // 黑色
        //shadowEffect->setBlurRadius(10);
        //this->setGraphicsEffect(shadowEffect);
     //设置bodyleft图标和文本
        ui->rec->setIconAndText(":/rec3.png","推荐",0);
        ui->radio->setIconAndText(":/radio2.png","电台",1);
        ui->music->setIconAndText(":/music2.png","音乐馆",2);
        ui->like->setIconAndText(":/like2.png","我喜欢",3);
        ui->local->setIconAndText(":/local33.png"," 本地下载",4);
        ui->recent->setIconAndText(":/recent2.png","最近播放",5);
        //本地下载BtForm动画默认显示
        ui->local->showAnimation();
        ui->stackedWidget->setCurrentIndex(3);
        currentPage=ui->likePage;

        //初始化推荐页面
        srand(time(NULL));
        ui->recMusicBox->initRecBoxItem(randPiction(),1);
        ui->recMusicBox2->initRecBoxItem(randPiction(),2);
        //设置CommonPage信息
        ui->likePage->setMusicListType(PageType::LIKE_PAGE);
        ui->likePage->setCommonPageUI("我喜欢",":/ilikebg2.png");
        ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
        ui->localPage->setCommonPageUI("本地下载",":/localbg2.png");
        ui->recentPage->setMusicListType(PageType::RECENT_PAGE);
        ui->recentPage->setCommonPageUI("最近播放",":/recentbg2.png");
        //设置播放控制区图标
        ui->playMusic->setIcon(QIcon(":/play_33.png"));
        ui->playBackMode->setIcon(QIcon(":/shuffle4.png"));
        //创建volumeTool对象
        volumeTool=new VolumeTool(this);
        //创建lrcPage对象
        Lrcpage=new lrcpage(this);
        Lrcpage->hide();
        //创建lrcpageAnimation动画对象
        lrcpageAnimation=new QPropertyAnimation(Lrcpage,"geometry",this);
        lrcpageAnimation->setDuration(400);
        lrcpageAnimation->setStartValue(QRect(Lrcpage->x(),Lrcpage->height(),Lrcpage->width(),Lrcpage->height()));
        lrcpageAnimation->setEndValue(QRect(Lrcpage->x(),0,Lrcpage->width(),Lrcpage->height()));
        //lrcpageAnimation->setKeyValues(QRect(Lrcpage->x(),Lrcpage->height()/2,Lrcpage->width(),Lrcpage->height()));
}

void MYMusic::InitPlayer()
{
    //初始化媒体播放相关类的对象
    player=new QMediaPlayer(this);
    playerList=new QMediaPlaylist(this);
    //设置播放模式
    playerList->setPlaybackMode(QMediaPlaylist::Random);
    //将播放列表设置到播放媒体对象中
    player->setPlaylist(playerList);
    //设置初始播放音量
    player->setVolume(20);
    //播放模式发生改变时的信号槽关联
    connect(playerList,&QMediaPlaylist::playbackModeChanged,this,&MYMusic::onplaybackModeChanged);
    connect(playerList,&QMediaPlaylist::currentIndexChanged,this,&MYMusic::onCurrentIndexChanged);
    //播放歌曲改变时
    connect(player,&QMediaPlayer::durationChanged,this,&MYMusic::onDurationChanged);
    connect(player,&QMediaPlayer::positionChanged,this,&MYMusic::onPositionChanged);
    //播放对应pagetype页面包含的所有歌曲
    connect(ui->localPage,&CommonPage::playAll,this,&MYMusic::onplayALL);
    connect(ui->likePage,&CommonPage::playAll,this,&MYMusic::onplayALL);
    connect(ui->recentPage,&CommonPage::playAll,this,&MYMusic::onplayALL);
    //处理双击音乐
    connect(ui->localPage,&CommonPage::playMusicByIndex,this,&MYMusic::playMusicByIndex);
    connect(ui->likePage,&CommonPage::playMusicByIndex,this,&MYMusic::playMusicByIndex);
    connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&MYMusic::playMusicByIndex);
    //元数据发生改变时
    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&MYMusic::onMetaDataAvailableChanged);

}
void MYMusic::mouseMoveEvent(QMouseEvent *event)
{
    if(Qt::LeftButton==event->buttons())
    {
       move(event->globalPos()-dragmouse);
       return;
    }
    QWidget::mouseMoveEvent(event);
}

void MYMusic::mousePressEvent(QMouseEvent *event)
{
    //记录鼠标相对于屏幕左上角的相对坐标
    if(Qt::LeftButton==event->button())
    {
        dragmouse=event->globalPos()-geometry().topLeft();
        return;
    }
    QWidget::mousePressEvent(event);
}


void MYMusic::on_close_clicked()
{
    close();
}

void MYMusic::OnbtFormClick(int id)// 切换page页面
{
   ui->stackedWidget->setCurrentIndex(id);
   //把背景颜色改回最初状态
   QList<BtForm*> btForm=this->findChildren<BtForm*>();
   for(auto BtForm:btForm)
   {
       if(BtForm->getPageId()!=id)
       {
           BtForm->clearbackground();
       }
   }
}

void MYMusic::connectSignalAndSlots()//处理信号和槽函数
{
   connect(ui->rec,&BtForm::btClick,this,&MYMusic::OnbtFormClick);
   connect(ui->radio,&BtForm::btClick,this,&MYMusic::OnbtFormClick);
   connect(ui->music,&BtForm::btClick,this,&MYMusic::OnbtFormClick);
   connect(ui->like,&BtForm::btClick,this,&MYMusic::OnbtFormClick);
   connect(ui->local,&BtForm::btClick,this,&MYMusic::OnbtFormClick);
   connect(ui->recent,&BtForm::btClick,this,&MYMusic::OnbtFormClick);
    //处理收藏或不收藏歌曲
   connect(ui->localPage,&CommonPage::updateLikeMusic,this,&MYMusic::updataLikeMusicAndPage);
   connect(ui->likePage,&CommonPage::updateLikeMusic,this,&MYMusic::updataLikeMusicAndPage);
   connect(ui->recentPage,&CommonPage::updateLikeMusic,this,&MYMusic::updataLikeMusicAndPage);
   //处理静音
   connect(volumeTool,&VolumeTool::setMusicMuted, this, &MYMusic::onSetMusicMuted);
   //处理音量变化
   connect(volumeTool,&VolumeTool::setMusicVolume, this, &MYMusic::setMusicVolume);
   //处理进度条变化
   connect(ui->processBar,&MusicSlider::setMusicSliderPosition,this,&MYMusic::onMusicSliderChanged);
   //处理点击歌词按钮
   connect(ui->lrcWordBtn,&QPushButton::clicked,this,&MYMusic::onLrcWordBtn);
}
QJsonArray MYMusic::randPiction()//将图片路径和文本导入Json键值对中
{
   QVector<QString> imageArr;
   imageArr<<"001.png"<<"003.png"<<"004.png"<<"005.png"<<"006.png"<<"007.png"
   <<"008.png"<<"009.png"<<"010.png"<<"011.png"<<"012.png"<<"013.png"
   <<"014.png"<<"015.png"<<"016.png"<<"017.png"<<"018.png"<<"019.png"
   <<"020.png"<<"021.png"<<"022.png"<<"023.png"<<"024.png"<<"025.png"
   <<"026.png"<<"027.png"<<"028.png"<<"029.png"<<"030.png"<<"031.png"
   <<"032.png"<<"033.png"<<"034.png"<<"035.png"<<"036.png"<<"037.png"
   <<"038.png"<<"039.png"<<"040.png"<<"002.png"<<"041.png"<<"0382.png";
   std::random_shuffle(imageArr.begin(),imageArr.end());
   QJsonArray arr;
   for(int i=0;i<imageArr.size();i++)
   {
       QJsonObject obj;
       obj.insert("path",":/"+imageArr[i]);


       QString text=QString("推荐-%1").arg(i,3,10,QChar('0'));
       obj.insert("text",text);

       arr.append(obj);
   }
   return arr;
}


void MYMusic::on_volume_clicked()
{
    //获取ui控件中volume的左上角坐标，并转化为全局坐标
    QPoint point=ui->volume->mapToGlobal(QPoint(0,0));
    //计算volumeTool需要移动到的位置
    QPoint volumeLeftTop=point-QPoint(volumeTool->width()/2,volumeTool->height());
    volumeLeftTop.setX(volumeLeftTop.x()+30);
    volumeLeftTop.setY(volumeLeftTop.y()+15);
    //移动volumeTool
    volumeTool->move(volumeLeftTop);
    //显示volumeTool
    volumeTool->show();
}

void MYMusic::on_addLocal_clicked()
{
   QFileDialog fileDialog(this);
   fileDialog.setWindowTitle("添加本地下载音乐");
   //设置默认的打开路径
   QDir dir(QDir::currentPath());
   dir.cdUp();
   QString Path=dir.path();
   Path+="/MYMusic/localMusic";
   fileDialog.setDirectory(Path);
   //设置过滤文件
   QStringList mimeTypeFilters;
   mimeTypeFilters<<"application/octet-stream";
   fileDialog.setMimeTypeFilters(mimeTypeFilters);
   //设置一次多开多个
   fileDialog.setFileMode(QFileDialog::ExistingFiles);
   //fileDialog.exec();
    if(QDialog::Accepted==fileDialog.exec())
    {
        //获取选中的文件
        QList<QUrl> url=fileDialog.selectedUrls();
        //url是选中的音乐文件的路径
        //将选中的文件信息添加到本地下载
        musicList.addMusicUrl(url);
        //将音乐更新到commonPage中的listWidget中
        //切换到本地下载页面
        ui->stackedWidget->setCurrentIndex(4);
        currentPage=ui->localPage;
         ui->localPage->refresh(musicList);
         //将本地下载的歌曲添加到媒体播放列表中
         ui->localPage->addMusicToPlayerlist(musicList,playerList);
    }

}

void MYMusic::on_min_clicked()
{
   showMinimized();
}

void MYMusic::on_max_clicked()
{
    showMaximized();
}

void MYMusic::updataLikeMusicAndPage(bool isLike, const QString &musicId)
{
    //修改歌曲状态
    auto it=musicList.findMusicByMusicId(musicId);
    if(it!=musicList.end())
    {
        it->setIsLike(isLike);
    }
    //更新歌曲页面音乐列表
    ui->localPage->refresh(musicList);
    ui->likePage->refresh(musicList);
    ui->recentPage->refresh(musicList);
}

void MYMusic::on_playMusic_clicked()
{
    if(QMediaPlayer::PlayingState==player->state())
    {
        player->pause();
        ui->playMusic->setIcon(QIcon(":/play_22.png"));
    }
    else if(QMediaPlayer::PausedState==player->state())
    {
        player->play();
        ui->playMusic->setIcon(QIcon(":/play_on2.png"));
    }
    else if(QMediaPlayer::StoppedState==player->state())
    {
      player->play();
      //ui->playMusic->setIcon(QIcon(":/play_on2.png"));
    }
    else
    {
        qDebug()<<"错误";
    }
    if(QMediaPlayer::PlayingState==player->state())
    {
        ui->playMusic->setIcon(QIcon(":/play_on2.png"));
    }

}

void MYMusic::on_playUp_clicked()
{
   playerList->previous();
}

void MYMusic::on_playDown_clicked()
{
    playerList->next();
}

void MYMusic::onLrcWordBtn()
{
    Lrcpage->show();
    lrcpageAnimation->start();
}

void MYMusic::on_playBackMode_clicked()
{
   if(playerList->playbackMode()==QMediaPlaylist::Loop)
   {
       //随机播放
       playerList->setPlaybackMode(QMediaPlaylist::Random);
       ui->playBackMode->setToolTip("随机播放");
   }
   else if(playerList->playbackMode()==QMediaPlaylist::Random)
   {
       //单曲循环
       playerList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
       ui->playBackMode->setToolTip("单曲循环");
   }
   else if(playerList->playbackMode()==QMediaPlaylist::CurrentItemInLoop)
   {
       //列表循环
       playerList->setPlaybackMode(QMediaPlaylist::Loop);
       ui->playBackMode->setToolTip("列表循环");
   }
   else
   {
       qDebug()<<"暂不支持";
   }
}

void MYMusic::onplaybackModeChanged(QMediaPlaylist::PlaybackMode playbackmode)
{
    if(playbackmode==QMediaPlaylist::Loop)
    {
        ui->playBackMode->setIcon(QIcon(":/listplay.png"));
    }
    else if(playbackmode==QMediaPlaylist::Random)
    {
        ui->playBackMode->setIcon(QIcon(":/shuffle4.png"));
    }
    else if(playbackmode==QMediaPlaylist::CurrentItemInLoop)
    {
        ui->playBackMode->setIcon(QIcon(":/singleplay.png"));
    }
    else
    {
        qDebug()<<"暂不支持该模式";
    }
}

void MYMusic::onplayALL(PageType pageType)
{
    CommonPage* page=ui->localPage;
    switch(pageType)
    {
     case PageType::LIKE_PAGE:
        page=ui->likePage;
        break;
    case PageType::LOCAL_PAGE:
        page=ui->localPage;
        break;
    case PageType::RECENT_PAGE:
        page=ui->recentPage;
        break;
    default:
        qDebug()<<"暂不支持该页面";
    }
    PlayAllMusicOfPage(page,0);
}

void MYMusic::PlayAllMusicOfPage(CommonPage *page, int index)
{
    currentPage=page;
   playerList->clear();
   page->addMusicToPlayerlist(musicList,playerList);
   playerList->setCurrentIndex(index);
   player->play();
}

void MYMusic::playMusicByIndex(CommonPage *page, int index)
{
    PlayAllMusicOfPage(page,index);
}

void MYMusic::onCurrentIndexChanged(int index)
{
    currentIndex=index;
    QString musicid=currentPage->getMusicidOfIndex(index);
    auto it=musicList.findMusicByMusicId(musicid);
    if(it!=musicList.end())
    {
        it->setIsHistory(true);
    }

    ui->recentPage->refresh(musicList);
}

void MYMusic::onSetMusicMuted(bool isMuted)
{
    player->setMuted(isMuted);
}

void MYMusic::setMusicVolume(int volumeRadio)
{
    player->setVolume(volumeRadio);
}

void MYMusic::onDurationChanged(qint64 duration)
{
    totalTime=duration;
  ui->totalTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0'))
                         .arg(duration/1000%60,2,10,QChar('0')));
}

void MYMusic::onPositionChanged(qint64 position)
{
    //更新进度条
    ui->processBar->setStep(position/(float)totalTime);
    //更新当前播放时间
    ui->currentTime->setText(QString("%1:%2").arg(position/1000/60,2,10,QChar('0'))
                             .arg(position/1000%60,2,10,QChar('0')));
    //同步更新歌词显示
    if(currentIndex>=0)
    {
        Lrcpage->showLrcWordLine(position);
    }
}

void MYMusic::onMusicSliderChanged(float ration)
{
    //根据当前进度与总进度比率更新播放时间
    qint64 duration=totalTime*ration;
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0'))
                           .arg(duration/1000%60,2,10,QChar('0')));
    //改变媒体源播放时间
    player->setPosition(duration);

}

void MYMusic::onMetaDataAvailableChanged(bool available)
{
    //歌曲名称
    //歌曲作者
    QString musicId=currentPage->getMusicidOfIndex(currentIndex);
    auto it=musicList.findMusicByMusicId(musicId);
    QString musicName("位置歌曲");
    QString musicSinger("未知歌手");
    if(it!=musicList.end())
    {
        musicName=it->getMusicName();
        musicSinger=it->getMusicSinger();
    }

    ui->musicName->setText(musicName);
    ui->musicSigner->setText(musicSinger);
    //设置封面图片
    QVariant coverImage=player->metaData("ThumbnailImage");
    if(coverImage.isValid())
    {
        QImage image=coverImage.value<QImage>();
        ui->musicPicture->setPixmap(QPixmap::fromImage(image));
        currentPage->setMusicImage(QPixmap::fromImage(image));
    }
    else
    {
        QString path=":/non-music.png";
        ui->musicPicture->setPixmap(path);
        currentPage->setMusicImage(path);
    }
    ui->musicPicture->setScaledContents(true);
    if(it!=musicList.end())
    {
        //解析歌曲LRC歌词
        //获取歌曲LRC文件路径
        QString musicLrcPath=it->getLrcFilePath();
        QString LrcMusicName=it->getMusicName();
        QString LrcMusicSinger=it->getMusicSinger();
        //解析LRC文件
        Lrcpage->praseFilePath(musicLrcPath,it->getMusicName(),it->getMusicSinger());
    }


}

